<template>
  <div class="training-plan-detail">
    <h2>训练计划详情</h2>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ plan.name }}</span>
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </template>
      <div class="plan-info">
        <p><strong>描述:</strong> {{ plan.description }}</p>
        <p><strong>开始日期:</strong> {{ plan.startDate }}</p>
        <p><strong>结束日期:</strong> {{ plan.endDate }}</p>
      </div>

      <el-divider>考核节点时间线</el-divider>
      <div ref="timelineChart" style="width: 100%; height: 400px"></div>

      <el-divider>考核节点管理</el-divider>
      <el-button type="primary" @click="openAddNodeModal">
        <i class="bi bi-plus-lg me-2"></i>添加考核节点
      </el-button>
      <el-table
        :data="plan.assessmentNodes"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="name" label="节点名称"></el-table-column>
        <el-table-column prop="date" label="日期">
          <template #default="scope">
            {{ dayjs(scope.row.date).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editNode(scope.row)">
              <i class="bi bi-pencil me-2"></i>编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteNode(scope.row)"
            >
              <i class="bi bi-trash me-2"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑考核节点模态框 -->
    <el-dialog
      v-model="showNodeModal"
      :title="isEditNodeMode ? '编辑考核节点' : '添加考核节点'"
      width="40%"
    >
      <el-form :model="currentNode" label-width="100px">
        <el-form-item label="节点名称">
          <el-input v-model="currentNode.name"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="currentNode.date"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNodeModal = false">取消</el-button>
          <el-button type="primary" @click="saveNode">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import * as echarts from "echarts";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

const plan = reactive({
  id: null,
  name: "",
  description: "",
  startDate: "",
  endDate: "",
  assessmentNodes: [],
});

const showNodeModal = ref(false);
const isEditNodeMode = ref(false);
const currentNode = reactive({
  id: null,
  name: "",
  date: null,
});

const timelineChart = ref(null);
let myChart = null;

// 模拟数据获取
const fetchPlanDetail = (id) => {
  // 实际应用中会从后端API获取数据
  const mockPlans = [
    {
      id: 1,
      name: "新员工入职培训计划",
      description: "针对新入职员工的全面培训",
      startDate: "2023-01-01",
      endDate: "2023-03-31",
      assessmentNodes: [
        { id: 101, name: "第一阶段考核", date: "2023-01-31" },
        { id: 102, name: "中期评估", date: "2023-02-28" },
        { id: 103, name: "结业考核", date: "2023-03-30" },
      ],
    },
    {
      id: 2,
      name: "高级护理技能提升",
      description: "提升高级护理人员的专业技能",
      startDate: "2023-04-01",
      endDate: "2023-06-30",
      assessmentNodes: [
        { id: 201, name: "理论考核", date: "2023-04-15" },
        { id: 202, name: "实践操作", date: "2023-05-10" },
      ],
    },
  ];
  const foundPlan = mockPlans.find((p) => p.id === parseInt(id));
  if (foundPlan) {
    // 将日期字符串转换为Date对象，以便el-date-picker正确显示
    const parsedPlan = {
      ...foundPlan,
      assessmentNodes: foundPlan.assessmentNodes.map((node) => ({
        ...node,
        date: node.date ? new Date(node.date) : null,
      })),
    };
    Object.assign(plan, parsedPlan);
  } else {
    // 处理未找到计划的情况，例如跳转回列表页
    router.push("/teacher/training-plan");
  }
};

const initChart = () => {
  if (timelineChart.value) {
    myChart = echarts.init(timelineChart.value);
    updateChart();
  }
};

const updateChart = () => {
  const dates = plan.assessmentNodes.map((node) =>
    dayjs(node.date).format("YYYY-MM-DD"),
  );
  const names = plan.assessmentNodes.map((node) => node.name);

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        let res = params[0].name + "<br/>";
        params.forEach((item) => {
          res += item.marker + item.seriesName + ": " + item.value + "<br/>";
        });
        return res;
      },
    },
    xAxis: {
      type: "category",
      data: dates.sort(), // 确保日期是排序的
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      show: false, // 隐藏Y轴，因为我们主要关注时间点
    },
    series: [
      {
        name: "考核节点",
        type: "scatter",
        symbolSize: 10,
        data: dates.map((date, index) => [
          date,
          1, // 所有点都在Y轴的同一高度
        ]),
        label: {
          show: true,
          formatter: function (params) {
            return names[dates.indexOf(params.name)];
          },
          position: "top",
        },
        itemStyle: {
          color: "#0d6efd",
        },
      },
      {
        name: "时间线",
        type: "line",
        data: dates.map((date) => [date, 1]),
        lineStyle: {
          color: "#ccc",
        },
        symbol: "none",
      },
    ],
  };
  myChart.setOption(option);
};

const openAddNodeModal = () => {
  isEditNodeMode.value = false;
  Object.assign(currentNode, { id: null, name: "", date: null }); // date初始化为null
  showNodeModal.value = true;
};

const saveNode = () => {
  if (isEditNodeMode.value) {
    const index = plan.assessmentNodes.findIndex(
      (node) => node.id === currentNode.id,
    );
    if (index !== -1) {
      plan.assessmentNodes[index] = {
        ...currentNode,
        date: dayjs(currentNode.date).format("YYYY-MM-DD"),
      };
    }
  } else {
    currentNode.id =
      plan.assessmentNodes.length > 0
        ? Math.max(...plan.assessmentNodes.map((node) => node.id)) + 1
        : 1;
    plan.assessmentNodes.push({
      ...currentNode,
      date: dayjs(currentNode.date).format("YYYY-MM-DD"),
    });
  }
  showNodeModal.value = false;
  updateChart(); // 更新图表
};

const editNode = (node) => {
  isEditMode.value = true;
  // 确保日期是Date对象，以便el-date-picker正确显示
  Object.assign(currentNode, {
    ...node,
    date: node.date ? new Date(node.date) : null,
  });
  showNodeModal.value = true;
};

const deleteNode = (node) => {
  plan.assessmentNodes = plan.assessmentNodes.filter((n) => n.id !== node.id);
  updateChart(); // 更新图表
};

const goBack = () => {
  router.push("/teacher/training-plan");
};

onMounted(() => {
  fetchPlanDetail(route.params.id);
  initChart();
});

watch(
  () => plan.assessmentNodes,
  () => {
    updateChart();
  },
  { deep: true },
);
</script>

<style scoped>
.training-plan-detail {
  padding: 20px;
}

.box-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.plan-info p {
  margin-bottom: 8px;
}

.dialog-footer button {
  margin-left: 10px;
}
</style>
